package com.thudojsc.canvasengine.entity;

import java.util.LinkedList;

import android.util.SparseArray;

import com.thudojsc.canvasengine.touch.ITouchArea;
import com.thudojsc.canvasengine.touch.TouchEvent;

public class Scene extends Node {
	private SparseArray<ITouchArea> mTouchAreaBindings = new SparseArray<ITouchArea>();
	private LinkedList<ITouchArea> mTouchAreas = new LinkedList<ITouchArea>();
	
	public void registerTouchArea(final ITouchArea pTouchArea) {
		this.mTouchAreas.add(pTouchArea);
	}
	
	public void unregisterTouchArea(final ITouchArea pTouchArea) {
		this.mTouchAreas.remove(pTouchArea);
	}
	
	public boolean onSceneTouchEvent(final TouchEvent pSceneTouchEvent) {
		final boolean isActionDown = pSceneTouchEvent.isActionDown();
		//Not Action Down
		
		
		if (!isActionDown) {
			final SparseArray<ITouchArea> touchAreaBindings = this.mTouchAreaBindings;
			final ITouchArea boundTouchArea = touchAreaBindings.get(pSceneTouchEvent.getPointerID());
			
			if (boundTouchArea != null) {
				final int action = pSceneTouchEvent.getAction();
				
				switch (action) {
				case TouchEvent.ACTION_UP:
				case TouchEvent.ACTION_CANCEL:
					touchAreaBindings.remove(pSceneTouchEvent.getPointerID());
				}
				
				boundTouchArea.onTouchEvent(pSceneTouchEvent, pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
				
				return true;
			}
		}
		//Action Touch Down and Move
		final LinkedList<ITouchArea> touchAreas = this.mTouchAreas;
		
		final int touch_count = touchAreas.size();
		
		for (int i = touch_count - 1; i >= 0; i--) {
			final ITouchArea touchArea = touchAreas.get(i);
			
			if ( touchArea.contain(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()) && isActionDown) {
				
				if (touchArea.onTouchEvent(pSceneTouchEvent, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()))
					mTouchAreaBindings.put(pSceneTouchEvent.getPointerID(), touchArea);
				
				return true;
			}
			
		}
		
		return false;
	}
}
